(ns web.coretest
  (:use clojure.test
	ring.mock.request
	clj.jtacck.web.core)
  (:require [clj.jtacck.db.core :as db])
  (:import jvm.jtacck.Util))

(def db-username (System/getProperty "test.dbuser"))
(def db-password (System/getProperty "test.dbpass"))
(def db-server (System/getProperty "test.dbserver"))
(def db-port (System/getProperty "test.dbport"))
(def db-name (System/getProperty "test.dbname"))
(def db-uri (str db-server ":" db-port "/" db-name))
(def db-sqlpath (System/getProperty "test.dbsqlpath"))


(defn- start-db []
  (db/start-db-connection db-username db-password db-uri)
  (Util/setUp))

(defn- stop-db []
  (Util/tearDown)
  (db/stop-db-connection))

(deftest login-reroute-test
  (let [uris ["/" "/anything" "/add/specimen"
	      "/add/shipment" "lab-graph.png"]]
    (doseq [uri uris
	    action [:get :post :put]]
      (is (= (app (request action uri))
	     {:status 302 :headers {"Location" "/login"} :body ""})))))

(defn login
  "Does a HTTP request to login with the given credential."
  [username password]
  (app (request :post "/login"
		{:pclc_submit "Login"
		 :pclc_user_name username
		 :pclc_password password})))

(deftest login-test
  (start-db)
  (is (= (login "rtiarsntoiecxnvzrst123" "test")
	 {:status 200
	  :headers {"Content-Type" "text/html"}
	  :body "Username/Password combination unknown."}))
  (let [ret (login "cschroeder" "cody")
	ret (assoc ret :headers (select-keys (:headers ret)
					     ["Location"]))]
    (is (= ret
	   {:status 302 :headers {"Location" "/"} :body ""})))
  (stop-db))

(deftest root-test
  (start-db)
  (let [client-cookies (first (get-in (login "cschroeder" "cody")
				      [:headers "Set-Cookie"]))
	admin-cookies (first (get-in (login "admin" "admin")
				     [:headers "Set-Cookie"]))
	lab-cookies (first (get-in (login "lab" "lab")
				     [:headers "Set-Cookie"]))
	root-client (app (header (request :get "/")
				 :cookie client-cookies))
	root-lab (app (header (request :get "/")
			      :cookie lab-cookies))
	root-admin (app (header (request :get "/")
				:cookie admin-cookies))]
    (doseq [root [root-client root-lab root-admin]]
      (is (= (:status root) 200))))
  (stop-db))

(deftest not-found-test
  (start-db)
  (let [cookies (first (get-in (login "cschroeder" "cody")
			       [:headers "Set-Cookie"]))]
    (doseq [uri ["/nothing-here" "/some-place" "/index.html"
		 "/public/about.html" "/about.html"]]
     (is (= 404 (:status (app (header (request :get uri)
				      :cookie cookies)))))))
  (stop-db))

(deftest graph-test
  (start-db)
  (let [cookies (first (get-in (login "lab" "lab")
			       [:headers "Set-Cookie"]))]
    (is (= (select-keys (app (header (request :get "/lab-graph.png")
				     :cookie cookies))
			[:status :headers])
	   {:headers {"Content-Type" "image/png"
		      "Cache-Control" "private,no-cache,no-store"}
	    :status 200})))
  (stop-db))